// 1.导入jsonwebtoken和express-jwt模块
const jwt = require("jsonwebtoken");
const { expressjwt: expressJWT } = require("express-jwt");

const express = require("express");
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 2.定义秘钥。注册解析中间件
const secret = "secret";

// unless 的作用为排除某些路径不需要鉴权
// express-jwt 这个中间件注册成功之后，会将用户信息绑定到req上面，可以通过req.user获取
app.use(
  expressJWT({ secret: secret, algorithms: ["HS256"] }).unless({
    path: "/api/user/login",
  })
);

// 登录接口
app.post("/api/user/login", (req, res) => {
  console.warn(req.body);
  const username = req.body.username;
  const password = req.body.password;
  if (username === "admin" && password === "123456") {
    // 登录成功，生成token
    const token = jwt.sign({ username }, secret, { expiresIn: "60s" });
    res.send({
      code: 200,
      message: "登录成功",
      token,
    }); // 登录成功，返回token
  } else {
    res.send("用户名或密码错误");
  }
});

// 验证token
app.get("/api/user/info", (req, res) => {
  console.log(req);
  res.send(req.auth);
  //   res.send(req.user);
});

app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).send({
      code: 401,
      message: "token过期",
    });
  } else {
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

app.listen(3000, () => {
  console.log("server is running at port 3000");
});
